package cn.edu.zstu.qingzhu.qingzhushop.controller;

import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-11-07 23:11
 */
@SuppressWarnings("unchecked")
@ResponseBody
public class BaseRestController<S extends IService<T>,T,ID extends Serializable> {

    @Autowired
    protected S iService;

    public S getService(){
        return iService;
    }

    /**
     * 获取单个实体
     * @param id 实体ID
     * @return Object
     */
    @ApiOperation(value = "获取单个实体",notes = "获取单个实体")
    @RequestMapping(value = "/{id}",method = {RequestMethod.GET})
    public ResponseBean get(@PathVariable(value = "id") ID id){

        return ResponseBean.success("查询成功",iService.getById(id));
    }

    /**
     * 添加单个实体
     * @param body 实体实体
     * @return Object
     */
    @ApiOperation(value = "添加单个实体",notes = "添加单个实体")
    @RequestMapping(value = "/",method = {RequestMethod.POST})
    public ResponseBean post(@RequestBody T body){
        if(iService.save(body)){
            return ResponseBean.success("添加成功",body);
        }else{
            return ResponseBean.error("添加失败");
        }
    }

    /**
     * 更新单个实体
     * @param id 实体 ID
     * @param body 实体实体
     * @return Object
     */
    @ApiOperation(value = "更新单个实体",notes = "更新单个实体")
    @RequestMapping(value = "/{id}",method = {RequestMethod.PUT})
    public ResponseBean put(@PathVariable(value = "id") ID id,@RequestBody T body){
        if(iService.updateById(body)){
            return ResponseBean.success("更新成功");
        }else{
            return ResponseBean.error("更新失败");
        }
    }

    /**
     * 删除单个实体
     * @param id 实体ID
     * @return Object
     */
    @ApiOperation(value = "删除单个实体",notes = "删除单个实体")
    @RequestMapping(value = "/{id}",method = {RequestMethod.DELETE})
    public ResponseBean delete(@PathVariable(value = "id") ID id){
        if(iService.removeById(id)){
            return ResponseBean.success("删除成功");
        }else{
            return ResponseBean.error("删除失败");
        }
    }
}
